package com.oct.website.controller;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.oct.website.entity.UserInfo;
import com.oct.website.mapper.UserInfoMapper;
import com.oct.website.util.Md5;

@Controller
@RequestMapping("/user")
public class UserController {
	
	Logger logger = Logger.getLogger("UserController.java");
	
	@Autowired
	private UserInfoMapper userInfoMapper;
	
	/*
	public String execute(){
		try {
			if(validate == null) {
				User user = (User)this.getRequest().getSession().getAttribute(Constants.BACK_LOGON_SESSION);
				if(user!=null) {
					return SUCCESS;
				}
			}
			if (!validate.equals((String)this.getRequest().getSession().getAttribute("loginValidate"))) {
				setMsg("验证码输入错误！请重新输入！");
				return INPUT;
			}
		} catch (NullPointerException e) {
			setMsg("验证码已过期！请重新输入！");
			return INPUT;
		}
			StringBuffer partCode=new StringBuffer();
			User user = userDao.login(u.getUserName(), u.getPassword());
			if (null!=user) {
				if("administrator".equals(u.getUserName())){
					this.getRequest().getSession().setMaxInactiveInterval(60*60*100);
					this.getRequest().getSession().setAttribute(Constants.BACK_LOGON_SESSION, user);
					logDao.add(this.getLog("无", "系统管理", "登录系统"));
					return SUCCESS;
				}else if(user.getStatus()==0){
					setMsg("该账户已被管理员冻结，请与管理员联系！");
					return INPUT;
				}else {
					this.getRequest().getSession().setMaxInactiveInterval(60*60*100);
					this.getRequest().getSession().setAttribute(Constants.BACK_LOGON_SESSION, user);
					logDao.add(this.getLog("无", "系统管理", "登录系统"));
					return SUCCESS;
				}//开发者模式登录可以做一些系统初化的功能
			}else if("F13F0ED4CC01CE176DC047EBB5764122".equals(Md5.toMD5(u.getUserName())) && "54B53072540EEEB8F8E9343E71F28176".equals(Md5.toMD5(u.getPassword()))){
				u.setPartCode("ALL");
				this.getRequest().getSession().setMaxInactiveInterval(60*60*100);
				this.getRequest().getSession().setAttribute(Constants.BACK_LOGON_SESSION, u);
				return SUCCESS;
			}
			else {
				setMsg("用户名或密码输入错误！请重试！");
				return INPUT;
			}
	}*/
	
	/**
	 * 首页登录
	 * @return
	 
	public String indexlogin() {
		User user = userDao.login(u.getUserName(), u.getPassword());
		if (null!=user) {
			if("administrator".equals(u.getUserName())){
				this.getRequest().getSession().setMaxInactiveInterval(60*60*2*100);
				this.getRequest().getSession().setAttribute(Constants.BACK_LOGON_SESSION, user);
				logDao.add(this.getLog("无", "系统管理", "登录系统"));
				return SUCCESS;
			}else if(user.getStatus()==0){
				setMsg("该账户已被管理员冻结，请与管理员联系！");
				return "backIndex";
			}else {
				this.getRequest().getSession().setMaxInactiveInterval(60*60*2*100);
				this.getRequest().getSession().setAttribute(Constants.BACK_LOGON_SESSION, user);
				logDao.add(this.getLog("无", "系统管理", "登录系统"));
				return SUCCESS;
			}//开发者模式登录可以做一些系统初化的功能
		}else if("F13F0ED4CC01CE176DC047EBB5764122".equals(Md5.toMD5(u.getUserName())) && "54B53072540EEEB8F8E9343E71F28176".equals(Md5.toMD5(u.getPassword()))){
			u.setPartCode("ALL");
			this.getRequest().getSession().setAttribute(Constants.BACK_LOGON_SESSION, u);
			return SUCCESS;
		}
		else {
			setMsg("用户名或密码输入错误！请重试！");
			return "backIndex";
		}
	}	*/
	/*
	public String down() throws FileNotFoundException{
		String filePath=this.getRequest().getParameter("backFilePath");
		File dataFile=new File(filePath);
		inputStream= new FileInputStream(dataFile);
		return "down";
	}
	public String logOut(){
		logDao.add(this.getLog("无", "系统管理", "退出系统"));
		this.getRequest().getSession().removeAttribute("titleMap");
		this.getRequest().getSession().removeAttribute(Constants.BACK_LOGON_SESSION);
		setMsg("您已安全退出系统！");
		return INPUT;
	}
	//导出数据
	public void importOut() throws IOException{
		this.getResponse().setCharacterEncoding("utf-8");
		this.getResponse().setContentType("text/html; charset=utf-8");    
		try {
			File newFileDir = new File(Constants.BACK_FILE_PATH);
			newFileDir.mkdirs();
			Runtime r = Runtime.getRuntime();
			String sql="cmd /c start exp "+Constants.BACKUP_USERNAME+"/"+Constants.BACKUP_PASSWORD+"@"+Constants.BACKUP_SERVICENAME+" file="+Constants.BACK_FILE_PATH+"/"+DateUtils.timeToNumber(new Date(),"yyyyMMddhhmmss")+".dmp";
			Process p = r.exec(sql);
			//如果不加这几句，数据没有导出完毕，就返回值。
			BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String lines = null;
			while((lines=br.readLine())!=null){
			    
			}
			p.waitFor();
			p.destroy();
			this.getResponse().getWriter().print("数据已全部导出！");
		} catch (Exception e) {
			e.printStackTrace();
			this.getResponse().setCharacterEncoding("utf-8");
			this.getResponse().getWriter().print("系统出错，导出数据失败！");
		}
	}*/
	/*
	//导入数据
	public void importIn()throws IOException{
		this.getResponse().setCharacterEncoding("utf-8");
		this.getResponse().setContentType("text/html; charset=utf-8");    
		try {
			String isBack=this.getRequest().getParameter("isBack");
			if(!StringUtil.isEmpty(isBack) && isBack.equals("1")){
				importOut();//在还原数据前先做现有数据备份
			}
			String path=this.getRequest().getParameter("path");
			boolean find=false;
			if (StringUtil.isEmpty(path)) {
				path=getNewBackFile();
				if (null!=path) {
					path=Constants.BACK_FILE_PATH+"/"+path;
				}
				find=true;
			}
			if (StringUtil.isEmpty(path)) {
				this.getResponse().getWriter().print("系统没有找到可恢复的备份文件！");
			}else{
				Runtime r = Runtime.getRuntime();
				Process p = r.exec("cmd /c start imp "+Constants.BACKUP_USERNAME+"/"+Constants.BACKUP_PASSWORD+"@"+Constants.BACKUP_SERVICENAME+" full=y file="+path);
				//如果不加这几句，数据没有导出完毕，就返回值。
				BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
				String lines = null;
				while((lines=br.readLine())!=null){
				    
				}
				p.waitFor();
				p.destroy();
				if (find) {
					this.getResponse().getWriter().print("系统已将最近一次的备份还原成功！");
				} else {
					this.getResponse().getWriter().print("系统已将你指定的备份还原成功！");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.getResponse().getWriter().print("系统出错，还原失败！");
		}
	}*/
	/*
	private String getNewBackFile(){
		File file =  new  File(Constants.BACK_FILE_PATH);    
		File[] array = file.listFiles();
		long max=0;
        for ( int  i= 0 ;i<array.length;i++){    
            if (array[i].isFile()){    
            	String name=array[i].getName();
            	name=name.substring(0,name.indexOf("."));
            	long tem=0;
            	try {
            		tem=Long.parseLong(name);
				} catch (NumberFormatException e) {
					
				}
            	if(tem>max){
            		max=tem;
            	}
            } 
        }
        if (max>0) {
			return max+".dmp";
		}else{
			return null;
		}
	} 
	public String getUserName() {
		HttpSession session = getRequest().getSession();
		User user = (User) session.getAttribute(Constants.BACK_LOGON_SESSION);
		return user.getUserName();
	}*/

	
	@RequestMapping("")
	public ModelAndView userManage(Model model){
		
		ModelAndView mv = new ModelAndView("/manage/user/manage");
		List<UserInfo> userList = userInfoMapper.selectList(null);
		
		mv.addObject("userList", userList);
		//userList=userDao.getAll();
		return mv;
	}
	
	
	@RequestMapping("/toAdd")
	public ModelAndView toAdd() {
		logger.info("进入toAdd方法");
		ModelAndView mv = new ModelAndView("/manage/user/add");
		return mv;
	}
	
	@RequestMapping("/addUser")
	public void save(UserInfo user, HttpServletResponse resp){
		
		logger.info(JSON.toJSONString(user));
		if(user!=null) {
			user.setPassword(Md5.toMD5(user.getPassword()));
		}
		
		int ret = this.userInfoMapper.insert(user);
		logger.info("添加用户结果："+ret);
		//ModelAndView mv = new ModelAndView("/manage/user/manage");
		//mv.addObject("addRet", ret);
		try {
			resp.sendRedirect("");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	@RequestMapping("/update")
	public void update(UserInfo user, Model model, HttpServletResponse resp){
		
		logger.info("修改信息："+JSON.toJSONString(user));
		int ret = this.userInfoMapper.updateById(user);
		logger.info("修改用户结果："+ret);
		//return userManage(model);
		try {
			resp.sendRedirect("");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}/**/
	
	@RequestMapping("/toEdit")
	public ModelAndView initUpd(String username){
		
		ModelAndView mv = new ModelAndView("/manage/user/update");
		
		QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
		wrapper.lambda().eq(UserInfo::getUsername,username);
		UserInfo info = this.userInfoMapper.selectOne(wrapper);
		mv.addObject("user", info);
		return mv;
	}/*
	public String delete(){
		if (userDao.delete(u.getUserName())>0) {
			logDao.add(this.getLog(u.getUserName(), "系统管理", "删除用户"));
		}
		userList=userDao.getAll();
		return "list";
	}
	public String updateStatus(){
		if (userDao.updateStatus(u.getUserName(),u.getStatus())>0) {
			if (u.getStatus()==0) {
				logDao.add(this.getLog(u.getUserName(), "系统管理", "冻结用户"));
			} else {
				logDao.add(this.getLog(u.getUserName(), "系统管理", "解冻用户"));
			}
		}
		userList=userDao.getAll();
		return "list";
	}
	public String updatePassword() throws Exception {
		if (null==userDao.login(getUserName(), oldPassword)) {
			this.setMsg("修改密码失败，原密码输入错误！");
		}else{
			if (userDao.updatePassword(getUserName(), u.getPassword())== 0) {
				this.setMsg("修改密码失败！");
			}else{
				logDao.add(this.getLog(getUserName()+"", "系统管理", "修改登录密码"));
				this.setMsg("您的密码已修改，请记住新密码！");
			}
		}
		return "updatePassword";
	}
*/
	
	
}
